import { uploadFormData } from '@/services/FileService';
import { snapM7s } from '@/services/M7SSerivce';
import { getSelfGrowthId } from '@/services/MeetingService';
import { myLive } from '@/services/ObsService';
import { addVideo, scanSegmentRecord } from '@/services/RecordService';
import {
  InputSourceModelType,
  RecordDataType,
  SceneModelType,
  Size,
  modalData,
  osnSelectType,
  saveModelType,
} from '@/types';
import { useModel } from '@@/exports';
import {
  DownOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
  PlusOutlined,
  SettingOutlined,
  SoundOutlined,
  UpOutlined,
  VideoCameraFilled,
} from '@ant-design/icons';
import { ProFormDigit, ProFormSelect } from '@ant-design/pro-form';
import { useGetState, useMount } from 'ahooks';
import {
  Button,
  Dropdown,
  MenuProps,
  Slider,
  Space,
  Spin,
  message,
} from 'antd';
import classNames from 'classnames';
import dayjs from 'dayjs';
import { useEffect, useMemo, useRef, useState } from 'react';
import SVG from 'react-inlinesvg';
import { formatDate } from 'web-plugin-utils';
import styles from './index.less';
import { sceneType, transitionType } from './typeData';

let useMountFlag = false;
export default () => {
  const { patient, setPatient } = useModel('patient');

  const preview = useRef(null);
  const obsPreview = useRef(null);

  const [oprateList, setOprateList] = useState<string[]>([
    '开始直播',
    '开始录制',
    '抓拍',
    '设置',
  ]);

  const [senceList, setSenceList] = useState<SceneModelType[]>([]); //场景
  const [senceSelect, setSenceSelect] = useState<SceneModelType>({}); //选择场景
  const oldSceneName = useMemo(() => {
    return senceSelect.name;
  });
  const [sourceList, setSourceList] = useState<InputSourceModelType[]>([]); //源
  const [sourceSelect, setSourceSelect] = useState<InputSourceModelType>({}); //选择源

  const [transition, setTransition] = useState<{ type: string; Timer: number }>(
    {
      type: 'Cut',
      Timer: 300,
    },
  ); //选择源

  const [streamingStatus, setStreamingStatus] = useState(false); //开始直播

  const [soundData, setSoundData] = useState([]); //声音

  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  const [isMouseDown, setIsMouseDown] = useState(false); //鼠标是否按下
  const [startX, setStartX] = useState(0); //起始x坐标
  const [startY, setStartY] = useState(0); //起始y坐标
  const [currentX, setCurrentX] = useState(0); //移动x坐标值
  const [currentY, setCurrentY] = useState(0); //移动y坐标值
  const [previewDetail, setPreviewDetail] = useState({
    height: 0,
    width: 0,
    x: 0,
    y: 0,
  });
  const [canvasSize, setCanvasSize] = useState({
    canvasWidth: 0,
    canvasHeight: 0,
  });
  const [mainWindowSize, setMainWindowSize, getMainWindowSize] = useGetState<
    | {
        x: number;
        y: number;
        width: number;
        height: number;
      }
    | undefined
  >();
  const [sourceDetail, setSourceDetail] = useState({
    sourceHeight: 0,
    sourceWidth: 0,
    sourceX: 0,
    sourceY: 0,
    oldScale: 1,
  });
  const [moveType, setMoveType] = useState('default');
  useEffect(() => {
    if (!useMountFlag) {
      return;
    }
    const previewEl = document.getElementById('preview');
    const handleMouseDown = (e: any) => {
      const { height, width, x, y } = previewDetail;
      if (e.clientY < 170) {
        return;
      }
      const { canvasHeight, canvasWidth } = canvasSize;
      console.log(height, width, x, y);
      const scale = width / canvasWidth;
      const leftMargin = (getMainWindowSize()!.width - width) / 2;
      if (
        e.clientX >= x &&
        e.clientX <= x + width &&
        e.clientY >= y &&
        e.clientY <= y + height
      ) {
        setIsMouseDown(true);
        setStartX(e.clientX);
        setStartY(e.clientY);
        //获取点击坐标和起始坐标的差值
        window.osn.coordinateDifference(
          senceSelect.name,
          sourceSelect.name,
          e.clientX,
          e.clientY,
          leftMargin,
          scale,
        );
        //获取点击前的源信息
        const sourceSelectName = sourceSelect.name;
        if (sourceSelectName === null) {
          return;
        }
        const { sourceHeight, sourceWidth, sourceX, sourceY, oldScale } =
          window.tm?.ipcRenderer.sendSync('sourceDetailMessage', {
            senceSelect: senceSelect.name,
            sourceSelectName,
          });
        console.log(
          '获取点击前的源信息:',
          sourceHeight,
          sourceWidth,
          sourceX,
          sourceY,
          oldScale,
        );
        setSourceDetail({
          sourceHeight,
          sourceWidth,
          sourceX,
          sourceY,
          oldScale,
        });
      }
    };
    const handleMouseMove = (e: any) => {
      const { height, width, x, y } = previewDetail;
      if (e.clientY < 170) {
        return;
      }
      if (isMouseDown) {
        const { canvasHeight, canvasWidth } = canvasSize;
        const scale = width / canvasWidth;
        const leftMargin = (getMainWindowSize()!.width - width) / 2;
        const { sourceHeight, sourceWidth, sourceX, sourceY, oldScale } =
          sourceDetail;
        const clientX = sourceX;
        const clientY = sourceY;
        if (
          moveType === 'leftTop' ||
          moveType === 'centerTop' ||
          moveType === 'rightTop' ||
          moveType === 'leftCenter' ||
          moveType === 'rightCenter' ||
          moveType === 'leftDown' ||
          moveType === 'centerDown' ||
          moveType === 'rightDown'
        ) {
          //画布坐标
          //左上
          const leftTopOne = { sourceX: clientX, sourceY: clientY };
          //中上
          const centerTopOne = {
            sourceX: clientX + sourceWidth / 2,
            sourceY: clientY,
          };
          //右上
          const rightTopOne = {
            sourceX: clientX + sourceWidth,
            sourceY: clientY,
          };
          //左中
          const leftCenterOne = {
            sourceX: clientX,
            sourceY: clientY + sourceHeight / 2,
          };
          //右中
          const rightCenterOne = {
            sourceX: clientX + sourceWidth,
            sourceY: clientY + sourceHeight / 2,
          };
          //左下
          const leftDownOne = {
            sourceX: clientX,
            sourceY: clientY + sourceHeight,
          };
          //中下
          const centerDownOne = {
            sourceX: clientX + sourceWidth / 2,
            sourceY: clientY + sourceHeight,
          };
          //右下
          const rightDownOne = {
            sourceX: clientX + sourceWidth,
            sourceY: clientY + sourceHeight,
          };
          const realX = (e.clientX - leftMargin) / scale;
          const realY = (e.clientY - 190) / scale;
          if (moveType === 'leftTop') {
            const moveDistanceX = (realX - leftTopOne.sourceX) * 2;
            const lessenWidth = sourceWidth - moveDistanceX;
            const scaleFactor = (lessenWidth / sourceWidth) * oldScale;
            window.osn.mouseMovePosition(
              senceSelect.name,
              sourceSelect.name!,
              realX,
              realY,
              scaleFactor,
            );
          } else if (moveType === 'centerTop') {
            const moveDistanceY = (realY - centerTopOne.sourceY) * 2;
            const lessenHeight = sourceHeight - moveDistanceY;
            const scaleFactor = (lessenHeight / sourceHeight) * oldScale;
            window.osn.mouseMovePosition(
              senceSelect.name,
              sourceSelect.name!,
              centerTopOne.sourceX,
              realY,
              scaleFactor,
            );
          } else if (moveType === 'rightTop') {
            const moveDistanceX = (realX - rightTopOne.sourceX) * 2;
            const lessenWidth = sourceWidth + moveDistanceX;
            const scaleFactor = (lessenWidth / sourceWidth) * oldScale;
            window.osn.mouseMovePosition(
              senceSelect.name,
              sourceSelect.name!,
              realX,
              realY,
              scaleFactor,
            );
          } else if (moveType === 'leftCenter') {
            const moveDistanceX = (realX - leftCenterOne.sourceX) * 2;
            const lessenWidth = sourceWidth - moveDistanceX;
            const scaleFactor = (lessenWidth / sourceWidth) * oldScale;
            window.osn.mouseMovePosition(
              senceSelect.name,
              sourceSelect.name!,
              realX,
              leftCenterOne.sourceY,
              scaleFactor,
            );
          } else if (moveType === 'rightCenter') {
            const moveDistanceX = (realX - rightCenterOne.sourceX) * 2;
            const lessenWidth = sourceWidth + moveDistanceX;
            const scaleFactor = (lessenWidth / sourceWidth) * oldScale;
            window.osn.mouseMovePosition(
              senceSelect.name,
              sourceSelect.name!,
              realX,
              rightCenterOne.sourceY,
              scaleFactor,
            );
          } else if (moveType === 'leftDown') {
            const moveDistanceX = (realX - leftDownOne.sourceX) * 2;
            const lessenWidth = sourceWidth - moveDistanceX;
            const scaleFactor = (lessenWidth / sourceWidth) * oldScale;
            window.osn.mouseMovePosition(
              senceSelect.name,
              sourceSelect.name!,
              realX,
              realY,
              scaleFactor,
            );
          } else if (moveType === 'centerDown') {
            const moveDistanceY = (realY - centerDownOne.sourceY) * 2;
            const lessenHeight = sourceHeight + moveDistanceY;
            const scaleFactor = (lessenHeight / sourceHeight) * oldScale;
            window.osn.mouseMovePosition(
              senceSelect.name,
              sourceSelect.name!,
              centerDownOne.sourceX,
              realY,
              scaleFactor,
            );
          } else if (moveType === 'rightDown') {
            const moveDistanceX = (realX - rightDownOne.sourceX) * 2;
            const lessenWidth = sourceWidth + moveDistanceX;
            const scaleFactor = (lessenWidth / sourceWidth) * oldScale;
            window.osn.mouseMovePosition(
              senceSelect.name,
              sourceSelect.name!,
              realX,
              realY,
              scaleFactor,
            );
          }
        } else if (moveType === 'pointer') {
          //移动
          setCurrentX(e.clientX);
          setCurrentY(e.clientY);
          const realX = (e.clientX - leftMargin) / scale;
          const realY = (e.clientY - 190) / scale;
          window.osn.mouseMovePosition(
            senceSelect.name,
            sourceSelect.name!,
            realX,
            realY,
            0,
          );
        }
      } else {
        //控制鼠标样式
        if (
          senceSelect &&
          sourceSelect &&
          senceSelect.name &&
          sourceSelect.name
        ) {
          const { canvasHeight, canvasWidth } = canvasSize;
          const scale = width / canvasWidth;

          const leftMargin = (getMainWindowSize()!.width - width) / 2;
          if (
            e.clientX >= x &&
            e.clientX <= x + width &&
            e.clientY >= y &&
            e.clientY <= y + height
          ) {
            const sourceSelectName = sourceSelect.name;
            if (sourceSelectName === null) {
              return;
            }
            const { sourceHeight, sourceWidth, sourceX, sourceY, oldScale } =
              window.tm?.ipcRenderer.sendSync('sourceDetailMessage', {
                senceSelect: senceSelect.name,
                sourceSelectName,
              });
            //左上实际坐标
            const clientX = sourceX * scale + leftMargin;
            const clientY = sourceY * scale + 190;
            const leftTopOne = { sourceX: clientX, sourceY: clientY };
            //中上
            const centerTopOne = {
              sourceX: clientX + (sourceWidth / 2) * scale,
              sourceY: clientY,
            };
            //右上
            const rightTopOne = {
              sourceX: clientX + sourceWidth * scale,
              sourceY: clientY,
            };
            //左中
            const leftCenterOne = {
              sourceX: clientX,
              sourceY: clientY + (sourceHeight / 2) * scale,
            };
            //右中
            const rightCenterOne = {
              sourceX: clientX + sourceWidth * scale,
              sourceY: clientY + (sourceHeight / 2) * scale,
            };
            //左下
            const leftDownOne = {
              sourceX: clientX,
              sourceY: clientY + sourceHeight * scale,
            };
            //中下
            const centerDownOne = {
              sourceX: clientX + (sourceWidth / 2) * scale,
              sourceY: clientY + sourceHeight * scale,
            };
            //右下
            const rightDownOne = {
              sourceX: clientX + sourceWidth * scale,
              sourceY: clientY + sourceHeight * scale,
            };
            if (
              leftTopOne.sourceX - e.clientX >= -5 &&
              leftTopOne.sourceX - e.clientX <= 5 &&
              leftTopOne.sourceY - e.clientY >= -5 &&
              leftTopOne.sourceY - e.clientY <= 5
            ) {
              window.osn.changeMouseCursor('nw-resize');
              setMoveType('leftTop');
            } else if (
              centerTopOne.sourceX - e.clientX >= -5 &&
              centerTopOne.sourceX - e.clientX <= 5 &&
              centerTopOne.sourceY - e.clientY >= -5 &&
              centerTopOne.sourceY - e.clientY <= 5
            ) {
              window.osn.changeMouseCursor('n-resize');
              setMoveType('centerTop');
            } else if (
              rightTopOne.sourceX - e.clientX >= -5 &&
              rightTopOne.sourceX - e.clientX <= 5 &&
              rightTopOne.sourceY - e.clientY >= -5 &&
              rightTopOne.sourceY - e.clientY <= 5
            ) {
              window.osn.changeMouseCursor('ne-resize');
              setMoveType('rightTop');
            } else if (
              leftCenterOne.sourceX - e.clientX >= -5 &&
              leftCenterOne.sourceX - e.clientX <= 5 &&
              leftCenterOne.sourceY - e.clientY >= -5 &&
              leftCenterOne.sourceY - e.clientY <= 5
            ) {
              window.osn.changeMouseCursor('w-resize');
              setMoveType('leftCenter');
            } else if (
              rightCenterOne.sourceX - e.clientX >= -5 &&
              rightCenterOne.sourceX - e.clientX <= 5 &&
              rightCenterOne.sourceY - e.clientY >= -5 &&
              rightCenterOne.sourceY - e.clientY <= 5
            ) {
              window.osn.changeMouseCursor('w-resize');
              setMoveType('rightCenter');
            } else if (
              leftDownOne.sourceX - e.clientX >= -5 &&
              leftDownOne.sourceX - e.clientX <= 5 &&
              leftDownOne.sourceY - e.clientY >= -5 &&
              leftDownOne.sourceY - e.clientY <= 5
            ) {
              window.osn.changeMouseCursor('ne-resize');
              setMoveType('leftDown');
            } else if (
              centerDownOne.sourceX - e.clientX >= -5 &&
              centerDownOne.sourceX - e.clientX <= 5 &&
              centerDownOne.sourceY - e.clientY >= -5 &&
              centerDownOne.sourceY - e.clientY <= 5
            ) {
              window.osn.changeMouseCursor('n-resize');
              setMoveType('centerDown');
            } else if (
              rightDownOne.sourceX - e.clientX >= -5 &&
              rightDownOne.sourceX - e.clientX <= 5 &&
              rightDownOne.sourceY - e.clientY >= -5 &&
              rightDownOne.sourceY - e.clientY <= 5
            ) {
              window.osn.changeMouseCursor('nw-resize');
              setMoveType('rightDown');
            } else if (
              (e.clientX >= leftTopOne.sourceX &&
                e.clientY >= leftTopOne.sourceY &&
                e.clientX <= rightDownOne.sourceX &&
                e.clientY <= rightDownOne.sourceY) ||
              (e.clientX <= leftTopOne.sourceX &&
                e.clientY <= leftTopOne.sourceY &&
                e.clientX >= rightDownOne.sourceX &&
                e.clientY >= rightDownOne.sourceY)
            ) {
              window.osn.changeMouseCursor('pointer');
              setMoveType('pointer');
            } else {
              window.osn.changeMouseCursor('Default');
              setMoveType('default');
            }
          }
        }
      }
    };
    const handleMouseUp = (e: any) => {
      const { height, width, x, y } = previewDetail;
      if (e.clientY < 170) {
        return;
      }
      setIsMouseDown(false);
      console.log(height, width, x, y);
      const scale = 1080 / height;
      setStartX(e.clientX);
      setStartY(e.clientY);
      setCurrentX(0);
      setCurrentY(0);
      window.osn.coordinateDifference(
        senceSelect.name,
        sourceSelect.name!,
        0,
        0,
        scale,
      );
      const sourceSelectName = sourceSelect.name;
      if (sourceSelectName != null) {
        const { sourceHeight, sourceWidth, sourceX, sourceY, oldScale } =
          window.tm?.ipcRenderer.sendSync('sourceDetailMessage', {
            senceSelect: senceSelect.name,
            sourceSelectName,
          });
        setSourceDetail({
          sourceHeight,
          sourceWidth,
          sourceX,
          sourceY,
          oldScale,
        });
      }
    };
    previewEl!.addEventListener('mousedown', handleMouseDown);
    previewEl!.addEventListener('mousemove', handleMouseMove);
    previewEl!.addEventListener('mouseup', handleMouseUp);

    return () => {
      previewEl!.removeEventListener('mousedown', handleMouseDown);
      previewEl!.removeEventListener('mousemove', handleMouseMove);
      previewEl!.removeEventListener('mouseup', handleMouseUp);
      // 在组件卸载时清除计时器
      if (timerInterval) {
        clearInterval(timerInterval);
      }
    };
  }, [isMouseDown, sourceSelect, previewDetail, moveType, sourceDetail]);

  const [timer, setTimer] = useState<NodeJS.Timer>(null);
  type deviceInfoType = { frameRate: number; CPU: number };

  const [deviceInfo, setDeviceInfo] = useState<deviceInfoType>({
    CPU: 0,
    frameRate: 20,
  });
  // useEffect(() => {
  //   // 定时任务逻辑
  //   const intervalId = setInterval(async () => {
  //     const result: deviceInfoType = await window.tm?.ipcRenderer.invoke(
  //       'performanceStatistics',
  //       {},
  //     );
  //     result.CPU = Math.round((result.CPU * 100) / 100);
  //     result.frameRate = Math.round((result.frameRate * 100) / 100);
  //     setDeviceInfo(result);
  //   }, 5000);
  //   setTimer(intervalId);
  //
  //   //监听窗口变化
  //   const handleWindowResize = async () => {
  //     const result = await setupPreview();
  //     setPreviewDetail(result);
  //     const mainWindowSize = await window.tm?.ipcRenderer.invoke(
  //       'getMainWindowSize',
  //       {},
  //     );
  //     setMainWindowSize(mainWindowSize);
  //   };
  //   window.addEventListener('resize', handleWindowResize);
  //   return () => {
  //     window.removeEventListener('resize', handleWindowResize);
  //     if (timer) {
  //       clearInterval(timer);
  //     }
  //   };
  // }, []);

  //obs推流唯一标识
  const [selfGrowthId, setSelfGrowthId] = useState('');
  useEffect(() => {
    //推流唯一标识
    getSelfGrowthIdInfo();
  }, []);
  //推流唯一标识
  const getSelfGrowthIdInfo = async () => {
    const result = await getSelfGrowthId(peerServer);
    if (result.status == 200) {
      console.log('setSelfGrowthId', result.data);
      setSelfGrowthId(result.data);
    }
  };

  const [recordData, setRecordData] = useState<RecordDataType | any>({});
  const { peerServer, m7sServer, obsPushServer } = useModel('global');
  const { initialState } = useModel('@@initialState');
  const [liveId, setLiveId] = useState<string>('');
  const streaming = async () => {
    if (!patient || !patient.id) {
      message.error('请先选择一个患者');
      return;
    }

    await window.tm?.ipcRenderer.invoke('update-rtmp', {
      server: obsPushServer + '/live-' + selfGrowthId,
      key: 'livestream-' + selfGrowthId,
    });
    await window.tm?.ipcRenderer.invoke('toggleStreaming', streamingStatus);
    if (!streamingStatus) {
      oprateList.splice(0, 1, '结束直播');
      console.log('开始直播');
      await window.tm?.ipcRenderer.invoke('setLiving', true);
      setOprateList(oprateList);
      startTimer();
      //保存直播地址
      console.log('===========', {
        livePath: `${obsPushServer}/live-${selfGrowthId}/livestream-${selfGrowthId}`,
        app: `live-${selfGrowthId}`,
        stream: `livestream-${selfGrowthId}`,
      });
      myLive(peerServer, {
        livePath: `${obsPushServer}/live-${selfGrowthId}/livestream-${selfGrowthId}`,
        app: `live-${selfGrowthId}`,
        stream: `livestream-${selfGrowthId}`,
      })
        .then((res) => {
          setLiveId(res.data.data);
        })
        .catch((e) => {
          message.error('保存直播地址出错！');
        });
      //m7s向srs拉流
      // 拉流的streamPath不变  streamPath=live/stream
      fetch(
        `${m7sServer}/rtmp/api/pull?target=${obsPushServer}/live-${selfGrowthId}/livestream-${selfGrowthId}&streamPath=live-${selfGrowthId}/livestream-${selfGrowthId}&save=0`,
      )
        .then((data) => {
          console.log('m7s拉流结果', data);
        })
        .catch((error) => {
          console.error('m7s拉流错误信息：', error);
          message.error('m7s服务错误！');
        });
    } else {
      console.log('结束直播');
      oprateList.splice(0, 1, '开始直播');
      await window.tm?.ipcRenderer.invoke('setLiving', false);
      setOprateList(oprateList);
      myLive(peerServer, {
        id: liveId,
      });
      // streamingButton.innerText = '开始直播';
      clearInterval(timerInterval);
      setLiveStatus(false);
    }
    setStreamingStatus(!streamingStatus);
  };
  const operateHandle = async (text: string, index: number) => {
    let result;
    if (text === '测试') {
      result = await window.tm?.ipcRenderer.invoke('test', sourceSelect?.name);
      console.log('test', result);
    }
    if (index === 0) {
      await streaming();
    }
    if (text === '设置') {
      console.log('设置');
      await dynamicView('/ObsManager/setting', {});
    }
    if (text === '抓拍') {
      await cutImg();
    }
  };
  const cutImg = async () => {
    if (!patient) {
      message.error('请先选择一个患者');
      return;
    }
    if (!streamingStatus) {
      message.error('请先开始直播');
      return;
    }
    const blob = await snapM7s(
      m7sServer,
      `live-${selfGrowthId}/livestream-${selfGrowthId}`,
    );

    const query = JSON.parse(localStorage.getItem('userInfo')!);
    const formData = new FormData();
    if (blob) {
      formData.append(
        'file',
        blob,
        `${dayjs().valueOf()}-${query.id}-${patient!.id}.jpg`,
      );
    } else {
      message.error('获取截图失败');
      return;
    }
    console.log('formData', formData);
    let resultUpload;
    try {
      resultUpload = await uploadFormData(peerServer, formData);
      console.log('resultUpload', resultUpload);
      const result = resultUpload.data;
      console.log('result', result);
      if (result && result.status === 200) {
        const data = result.data;
        const fileData = {
          patientId: patient!.id,
          fileName: data.fileName,
          fileUrl: data.fileUrl,
          fileTime: 0,
          fileSize: data.fileSize,
          fileType: 1,
          recordTimeNode: dayjs(Date.now()).format('YYYY-MM-DD hh:mm:ss'),
          recordTime: dayjs(Date.now()).format('YYYY-MM-DD hh:mm:ss'),
          uploadType: 0,
        };
        console.log('fileData', fileData);
        const videoResult = await addVideo(peerServer, fileData);
        console.log('videoResult', videoResult);
        if (videoResult.success) {
          message.success('截图已上传');
        } else {
          message.error('截图失败');
        }
      } else {
        message.error('截图失败');
      }
    } catch (e) {
      console.log('resultUpload', e.message);
      message.error('截图失败');
      return;
    }
  };
  const [recordTypeText, setRecordTypeText] = useState('');
  const [recordVideoId, setRecordVideoId] = useState('');

  const recordVideo = async (
    text: string,
    index: number,
    recordType: string,
  ) => {
    if (text === '开始录制') {
      if (recordType === 'cloudRecord') {
        const fileName = formatDate(
          new Date(),
          'yyyy-MM-dd-hh-mm-ss',
        ).toString();
        console.log('fileName', fileName);
        fetch(
          `${m7sServer}/record/api/start?type=mp4&streamPath=live-${selfGrowthId}/livestream-${selfGrowthId}&fileName=${fileName}&fragment=900s`,
        )
          .then(async (data) => {
            console.log('start to LiveId', data);
            if (data.status == 200) {
              console.log('LiveId', data);
              message.info('云录制开始');
              recordData.fileName = fileName;
              recordData.fileUrl = `${m7sServer}/record/mp4/live-${selfGrowthId}/livestream-${selfGrowthId}/${recordData.fileName}`;
              recordData.uploadType = 1;
              recordData.m7sRecordId = `live-${selfGrowthId}/livestream-${selfGrowthId}/mp4`;
              recordData.recordEquipmentIp = initialState!.m7sServerIp;
              recordData.patientId = patient!.id;
              const result = await addVideo(peerServer, recordData);
              if (result.status == 200) {
                setRecordVideoId(result.data);
              }
              setRecordData(recordData); //保存录制数据
            } else {
              message.error('云录制异常');
            }
          })
          .catch((error) => {
            console.error('云录制失败：', error);
            message.error('云录制异常');

            oprateList.splice(1, 1, '开始录制');
            console.log('oprateList', oprateList);
            setOprateList(
              oprateList.map((item, _index) =>
                _index === 1 ? '开始录制' : item,
              ),
            );
          });
      } else {
        const result = await window.osn?.startRecording();
        console.log('录制：', result);
        message.info('本地录制开始');
      }
    } else if (text === '停止录制') {
      if (recordType === 'cloudRecord') {
        fetch(
          `${m7sServer}/record/api/stop?id=live-${selfGrowthId}/livestream-${selfGrowthId}/mp4`,
        )
          .then((data) => {
            console.log('stop to LiveId', data);
            if (data.status == 200) {
              message.info('云录制已结束');
              //结束录制后，视频分片处理
              scanSegmentRecord(peerServer, recordVideoId);
              setRecordData({});
            } else {
              message.error('云录制结束异常');
            }
          })
          .catch((error) => {
            console.error('3333', error);
            message.error('云录制结束异常');

            oprateList.splice(1, 1, '停止录制');
            console.log('oprateList', oprateList);
            setOprateList(
              oprateList.map((item, _index) =>
                _index === 1 ? '停止录制' : item,
              ),
            );
          });
      } else {
        const result = await window.osn?.stopRecording();
        console.log('录制：', result);
        message.info('本地录制结束');
      }
    }
    oprateList.splice(1, 1, text === '开始录制' ? '停止录制' : '开始录制');
    console.log('oprateList', oprateList);
    setOprateList(
      oprateList.map((item, _index) =>
        _index === 1 ? (text === '开始录制' ? '停止录制' : '开始录制') : item,
      ),
    );
  };
  const initData = async () => {
    let allScene: SceneModelType[] =
      await window.tm!.ipcRenderer.invoke('getAllScene');
    console.log('allScene', allScene);
    setSenceList(allScene);
    let selectData: osnSelectType =
      await window.tm!.ipcRenderer.invoke('getOsnSelect');
    console.log('selectData', selectData);
    setSenceSelect(selectData.selectScene);
    let source = allScene.find(
      (item) => item.name === selectData.selectScene?.name,
    )?.items;
    console.log('source', source);
    setSourceList(source);
    console.log('selectData.selectSource ?? {}', selectData.selectSource ?? {});
    setSourceSelect(selectData.selectSource ?? {});
    console.log('newScene', selectData.selectScene.name);
    // await window.tm?.ipcRenderer.invoke(
    //   'changeScene',
    //   selectData.selectScene.name,
    //   selectData.selectSource?.name,
    // );

    // setSourceSelect(x)
    // window.osn.selectSource(senceSelect.name, x.name);
  };
  const setupPreview = async () => {
    const { width, height, x, y } = obsPreview.current.getBoundingClientRect();
    const result = await window.tm?.ipcRenderer.invoke('preview-init', {
      width,
      height,
      x,
      y,
    });
    preview.width = `${result.width}px`;
    setPreviewDetail(result);
    const { screenWidth, screenHeight } = await window.tm?.ipcRenderer.invoke(
      'getObsCanvasSize',
      {},
    );
    setCanvasSize({ canvasWidth: screenWidth, canvasHeight: screenHeight });
    const mainWindowSize = await window.tm?.ipcRenderer.invoke(
      'getMainWindowSize',
      {},
    );
    setMainWindowSize(mainWindowSize);
    return result;
  };
  const [initing, setIniting] = useState(true);
  useMount(async () => {
    const ro = new ResizeObserver(window.osn?.resizePreview);
    if (obsPreview) {
      ro.observe(obsPreview.current);
    }
    await window.osn.initOBS(preview);
    const previewSize = await setupPreview();
    if (previewSize && preview.current) {
      setIniting(false);
    } else {
      return;
    }
    await initData();

    const sound = await window.tm?.ipcRenderer.invoke('getAudio');
    console.log('sound', sound);

    setSoundData(sound);

    const saveData: saveModelType =
      await window.tm?.ipcRenderer.invoke('getSaveData');
    console.log('saveData', saveData);
    let trans = {
      type: saveData.defaultTransition.type,
      Timer: saveData.defaultTransition.timer,
    };
    console.log('trans', trans);
    setTransition(trans);

    // transition

    //实例化webSocket
    // 创建WebSocket连接
    const webSocket = new WebSocket('ws://localhost:8899'); // 替换为你的WebSocket服务器地址
    // 监听WebSocket事件
    webSocket.addEventListener('open', (event) => {
      console.log('WebSocket connection opened');
      // 在这里可以发送数据
      webSocket.send('Hello, server!');
    });
    webSocket.addEventListener('message', async (event) => {
      const messageData = JSON.parse(event.data);
      if (messageData.type === 'initData') {
        console.log('执行initData');
        await initData();
      }
    });
    webSocket.addEventListener('close', (event) => {
      console.log('WebSocket connection closed');
    });
    webSocket.addEventListener('error', (event) => {
      console.error('WebSocket error:', event);
    });
    useMountFlag = true;
  });

  const dynamicView = async (
    path: string,
    data: any,
    title?: string,
    option?: Size,
  ) => {
    const dynamicData: modalData = {
      path,
      data,
      title,
    };
    await window.tm?.ipcRenderer.invoke('showObsModal', dynamicData, option);
  };

  //LIVE 计时
  let seconds = 0;
  let minutes = 0;
  let hours = 0;
  let timerInterval: string | number | NodeJS.Timer | undefined;
  const [liveTime, setLiveTime] = useState('00:00:00');
  const [liveStatus, setLiveStatus] = useState(false);
  const startTimer = () => {
    console.log('liveTime', liveTime);
    clearInterval(timerInterval);
    setLiveStatus(false);
    seconds = 0;
    minutes = 0;
    hours = 0;
    setLiveTime('00:00:00');
    if (!liveStatus) {
      timerInterval = setInterval(updateTimer, 1000);
      setLiveStatus(true);
    }
  };
  const updateTimer = () => {
    seconds++;
    if (seconds === 60) {
      seconds = 0;
      minutes++;
      if (minutes === 60) {
        minutes = 0;
        hours++;
      }
    }
    setLiveTime(
      String(hours).padStart(2, '0') +
        ':' +
        String(minutes).padStart(2, '0') +
        ':' +
        String(seconds).padStart(2, '0'),
    );
  };

  return (
    <div className={styles.obs}>
      <div id={'obsPreview'} className={styles.obsPreview} ref={obsPreview}>
        <div id="preview" className={styles.preview} ref={preview}></div>
      </div>
      {initing && (
        <div id={'spinFull'} className={styles.spinFull}>
          <Spin size="large" />
        </div>
      )}
      <div className={styles.obsSetting}>
        {!initing && (
          <>
            <div className={styles.obsSettingBox}>
              <div className={styles.obsSettingBoxTop}>场景</div>
              <div className={styles.obsSettingBoxSelect}>
                <Space.Compact direction="vertical" className="">
                  {senceList.map((senceItem) => {
                    return (
                      <>
                        <div
                          style={{ padding: '10px' }}
                          className={classNames(styles.rowsItem, 'mouseColor', {
                            [styles['select']]:
                              senceSelect.name === senceItem.name,
                          })}
                          onClick={async () => {
                            setSenceSelect(senceItem);
                            const sourceList = senceItem.items;
                            setSourceList(sourceList);
                            setSourceSelect({});
                            console.log('transition', transition);
                            window.tm?.ipcRenderer.invoke(
                              'changeScene',
                              senceItem.name,
                            );
                          }}
                        >
                          {senceItem.name}
                        </div>
                      </>
                    );
                  })}
                </Space.Compact>
              </div>

              <div className={styles.obsSettingBoxOprate}>
                <PlusOutlined
                  className={'mouseColor'}
                  onClick={async () => {
                    await dynamicView(
                      '/ObsManager/sceneModal',
                      {
                        sceneName: senceSelect.name,
                      },
                      '添加场景',
                      {
                        width: 500,
                        height: 280,
                      },
                    );
                  }}
                />

                <SVG
                  style={{
                    width: '30px',
                    height: '30px',
                    backgroundColor: 'transparent',
                    fill: '#fff',
                    objectFit: 'fill',
                    marginBottom: '-4px',
                    cursor: 'pointer',
                  }}
                  className={'mouseColor'}
                  src="/img/meeting/delete.svg"
                  onClick={async () => {
                    if (senceList.length < 2) {
                      return;
                    }
                    await window.tm?.ipcRenderer.invoke(
                      'removeScene',
                      senceSelect.name,
                    );
                  }}
                />

                <UpOutlined
                  className={'mouseColor'}
                  onClick={async () => {
                    const result = await window.tm?.ipcRenderer.invoke(
                      'exChangeSort',
                      {
                        type: 'scene',
                        step: -1,
                      },
                    );
                    console.log('result', result);

                    const index = senceList.findIndex(
                      (item) => item.name === senceSelect.name,
                    );
                    console.log('index', index);
                    const stepIndex = index - 1;
                    if (stepIndex < 0) return;
                    let temp = senceList[index];
                    senceList[index] = senceList[stepIndex];
                    senceList[stepIndex] = temp;
                    setSenceList([...senceList]);
                    setSenceSelect({ ...senceList[stepIndex] });
                  }}
                />

                <DownOutlined
                  className={'mouseColor'}
                  onClick={async (e) => {
                    const result = await window.tm?.ipcRenderer.invoke(
                      'exChangeSort',
                      {
                        type: 'scene',
                        step: 1,
                      },
                    );
                    console.log('result', result);
                    const index = senceList.findIndex(
                      (item) => item.name === senceSelect.name,
                    );
                    console.log('index', index);
                    const stepIndex = index + 1;
                    if (stepIndex >= senceList.length) return;
                    let temp = senceList[index];
                    senceList[index] = senceList[stepIndex];
                    senceList[stepIndex] = temp;
                    setSenceList([...senceList]);
                    setSenceSelect({ ...senceList[stepIndex] });
                  }}
                />
              </div>
            </div>
            <div className={styles.obsSettingBox}>
              <div className={styles.obsSettingBoxTop}>来源</div>
              <div className={styles.obsSettingBoxSelect}>
                <Space.Compact direction="vertical">
                  {sourceList?.map((x) => {
                    return (
                      <>
                        <div
                          style={{ padding: '10px' }}
                          className={classNames(styles.rowsItem, 'mouseColor', {
                            [styles['select']]: sourceSelect?.name === x?.name,
                          })}
                          onClick={async () => {
                            setSourceSelect(x);
                            window.osn.selectSource(senceSelect.name, x.name);
                          }}
                        >
                          <span className={styles.sourceName}>
                            {x.aliasName}
                          </span>
                          <div>
                            {!x.visible && (
                              <EyeOutlined
                                onClick={async (e) => {
                                  e.preventDefault();
                                  e.stopPropagation();
                                  console.log('eys');
                                  const temp = sourceList.map((item) => {
                                    if (item.name === x.name) {
                                      item.visible = true;
                                    }
                                    return item;
                                  });
                                  setSourceList(temp);
                                  await window.tm?.ipcRenderer.invoke(
                                    'updateSceneItemSettings',
                                    {
                                      sceneName: senceSelect.name,
                                      name: x.name,
                                      updateSettings: {
                                        visible: true,
                                      },
                                    },
                                  );
                                }}
                              />
                            )}
                            {x.visible && (
                              <EyeInvisibleOutlined
                                onClick={async (e) => {
                                  e.preventDefault();
                                  e.stopPropagation();
                                  console.log('eys');
                                  const temp = sourceList.map((item) => {
                                    if (item.name === x.name) {
                                      item.visible = false;
                                    }
                                    return item;
                                  });
                                  setSourceList(temp);
                                  await window.tm?.ipcRenderer.invoke(
                                    'updateSceneItemSettings',
                                    {
                                      sceneName: senceSelect.name,
                                      name: x.name,
                                      updateSettings: {
                                        visible: false,
                                      },
                                    },
                                  );
                                }}
                              />
                            )}
                            {/* <LockOutlined/><UnlockOutlined/> */}
                            <SettingOutlined
                              style={{ marginLeft: '10px' }}
                              onClick={async () => {
                                sceneType.map(async (it) => {
                                  if (it.id == x.type) {
                                    console.log('it=============', it);
                                    console.log('xxxx=============', x);
                                    await dynamicView(it.path, {
                                      sceneName: senceSelect.name,
                                      id: x.id,
                                      name: x.name,
                                      isNew: false,
                                      // attributeData: result
                                    });
                                  }
                                });
                                // const result = await window.tm?.ipcRenderer.invoke('getSourceSettings', {
                                //     sceneName: senceSelect.name,
                                //     name: x.name
                                // })
                                // console.log("result", result)
                                // if (result) {
                                //     console.log("result111", result)
                                //     await dynamicView("/ObsManager/fontModal", {
                                //         sceneName: senceSelect.name,
                                //         id: x.id,
                                //         name: x.name,
                                //         isNew: false,
                                //         attributeData: result
                                //     });
                                // }
                              }}
                            />
                          </div>
                        </div>
                      </>
                    );
                  })}
                </Space.Compact>
              </div>
              <div className={styles.obsSettingBoxOprate}>
                <PlusOutlined
                  className={'mouseColor'}
                  onClick={async () => {
                    await dynamicView('/ObsManager/dataOriginTypeModal', {
                      sceneName: senceSelect.name,
                    });
                  }}
                />
                <SVG
                  style={{
                    width: '30px',
                    height: '30px',
                    backgroundColor: 'transparent',
                    fill: '#fff',
                    objectFit: 'fill',
                    marginBottom: '-4px',
                    cursor: 'pointer',
                  }}
                  className={'mouseColor'}
                  src="/img/meeting/delete.svg"
                  onClick={async () => {
                    if (!sourceSelect || !sourceSelect.name) {
                      console.log('请选择一个源');
                      message.error('请选择一个源');
                      return;
                    }
                    await window.tm?.ipcRenderer.invoke('removeSource', {
                      sceneName: senceSelect.name,
                      name: sourceSelect.name,
                    });
                  }}
                />

                <UpOutlined
                  className={'mouseColor'}
                  onClick={async () => {
                    if (!sourceSelect || !sourceSelect.name) {
                      console.log('请选择一个源');
                      message.error('请选择一个源');
                      return;
                    }
                    console.log(sourceSelect);
                    const index = senceSelect.items.findIndex(
                      (item) => item.name === sourceSelect.name,
                    );
                    const stepIndex = index - 1;
                    if (stepIndex < 0) return;
                    let temp = senceSelect.items[index];
                    senceSelect.items[index] = senceSelect.items[stepIndex];
                    senceSelect.items[stepIndex] = temp;
                    setSourceList([...senceSelect.items]);
                    const tempSenceList = senceList.map((item) => {
                      if (item.name === senceSelect.name) {
                        return senceSelect;
                      }
                      return item;
                    });
                    setSenceList([...tempSenceList]);
                    setSenceSelect({ ...senceSelect });
                    setSourceSelect({ ...senceSelect.items[stepIndex] });
                    await window.tm?.ipcRenderer.invoke('exChangeSort', {
                      type: 'source',
                      step: -1,
                    });
                  }}
                />

                <DownOutlined
                  className={'mouseColor'}
                  onClick={async () => {
                    if (!sourceSelect || !sourceSelect.name) {
                      console.log('请选择一个源');
                      message.error('请选择一个源');
                      return;
                    }
                    const index = senceSelect.items.findIndex(
                      (item) => item.name === sourceSelect.name,
                    );
                    const stepIndex = index + 1;
                    if (stepIndex >= senceSelect.items.length) return;
                    let temp = senceSelect.items[index];
                    senceSelect.items[index] = senceSelect.items[stepIndex];
                    senceSelect.items[stepIndex] = temp;
                    setSourceList([...senceSelect.items]);
                    const tempSenceList = senceList.map((item) => {
                      if (item.name === senceSelect.name) {
                        return senceSelect;
                      }
                      return item;
                    });
                    setSenceList([...tempSenceList]);
                    setSenceSelect({ ...senceSelect });
                    setSourceSelect({ ...senceSelect.items[stepIndex] });
                    await window.tm?.ipcRenderer.invoke('exChangeSort', {
                      type: 'source',
                      step: 1,
                    });
                  }}
                />
              </div>
            </div>
            <div className={styles.obsSettingBox}>
              <div className={styles.obsSettingBoxTop}>混音器</div>
              {soundData.map((sound, soundIndex) => {
                return (
                  <>
                    <div style={{ paddingTop: '5px', paddingLeft: '10px' }}>
                      <span>{sound.name}</span>
                    </div>
                    <div
                      style={{
                        paddingLeft: '5px',
                        display: 'flex',
                        flexDirection: 'row',
                      }}
                    >
                      <Slider
                        style={{ width: '85%' }}
                        value={sound.deflection}
                        max={100}
                        min={0}
                        tooltip={{ placement: 'bottom' }}
                        onChange={(value: number) => {
                          console.log('setFontSizeData', value);
                          soundData[soundIndex].deflection = value;
                          setSoundData(soundData.map((x) => x));
                          window.tm?.ipcRenderer.invoke('setupAudio', {
                            name: sound.name,
                            value: (value / 100).toFixed(2),
                          });
                        }}
                      />
                      {sound.deflection > 0 && (
                        <SoundOutlined
                          style={{ paddingLeft: '10px' }}
                          onClick={() => {
                            console.log('禁用');
                            window.tm?.ipcRenderer.invoke('setupAudio', {
                              name: sound.name,
                              value: 0,
                            });
                            soundData[soundIndex].deflection = 0;
                            setSoundData(soundData.map((x) => x));
                          }}
                        />
                      )}
                      {sound.deflection === 0 && (
                        <SoundOutlined
                          style={{ color: '#303030', paddingLeft: '10px' }}
                          onClick={() => {
                            console.log('开始');
                            setSoundData(soundData.map((x) => x));
                            window.tm?.ipcRenderer.invoke('setupAudio', {
                              name: sound.name,
                              value: 0.5,
                            });
                            soundData[soundIndex].deflection = 50;
                          }}
                        />
                      )}
                    </div>
                  </>
                );
              })}
            </div>
            <div className={styles.obsSettingBox}>
              <div className={styles.obsSettingBoxTop}>转场特效</div>
              <div style={{ width: '100%', padding: '0 10px' }}>
                <ProFormSelect
                  name="select"
                  label="转场"
                  options={transitionType}
                  fieldProps={{
                    allowClear: false,
                    listHeight: 180,
                  }}
                  defaultValue={'Cut'}
                  value={transition.type}
                  onChange={(value) => {
                    console.log('transition', value);
                    setTransition({
                      Timer: transition.Timer,
                      type: value,
                    });
                    window.tm?.ipcRenderer.invoke(
                      'updateTransition',
                      value,
                      transition.Timer,
                    );
                    console.log('value', value);
                  }}
                />
                <ProFormDigit
                  label="时长"
                  min={1}
                  step={1}
                  fieldProps={{
                    precision: 0,
                    addonAfter: <>ms</>,
                  }}
                  value={transition.Timer}
                  onChange={(value: number) => {
                    console.log('transitionTimer', value);

                    setTransition({
                      Timer: value,
                      type: transition.type,
                    });
                    window.tm?.ipcRenderer.invoke(
                      'updateTransition',
                      transition.type,
                      value,
                    );
                  }}
                />
              </div>
            </div>
            <div className={styles.obsSettingBox}>
              <div className={styles.obsSettingBoxTop}>控件</div>
              <div className={styles.obsSettingBoxSelect}>
                <Space.Compact
                  className={styles.obsSettingBoxOprate}
                  style={{ borderTop: 'none', borderBottom: 'none' }}
                  direction="vertical"
                >
                  {oprateList.map((text, index) => {
                    if (index === 1) {
                      const items: MenuProps['items'] = [
                        {
                          key: '本地录制',
                          label: (
                            <a
                              className={styles.recordButton}
                              onClick={async () => {
                                //设置录制类型
                                setRecordTypeText('localRecord');
                                await recordVideo(text, index, 'localRecord');
                              }}
                            >
                              本地录制
                            </a>
                          ),
                        },
                        {
                          key: '云录制',
                          label: (
                            <a
                              className={styles.recordButton}
                              onClick={async () => {
                                //设置录制类型
                                setRecordTypeText('cloudRecord');
                                await recordVideo(text, index, 'cloudRecord');
                              }}
                            >
                              云录制
                            </a>
                          ),
                        },
                      ];
                      if (text === '开始录制') {
                        return (
                          <Dropdown
                            key={'开始录制'}
                            menu={{ items }}
                            placement="top"
                          >
                            <Button key={text}>{text}</Button>
                          </Dropdown>
                        );
                      } else {
                        return (
                          <Button
                            onClick={async () => {
                              await recordVideo(text, index, recordTypeText);
                            }}
                            key={text}
                          >
                            {text}
                          </Button>
                        );
                      }
                    } else {
                      return (
                        <Button
                          onClick={async () => {
                            await operateHandle(text, index);
                          }}
                          key={text}
                        >
                          {text}
                        </Button>
                      );
                    }
                  })}
                </Space.Compact>
              </div>
            </div>
          </>
        )}
      </div>
      <div
        style={{
          width: '100%',
          height: '30px',
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'flex-end',
        }}
      >
        <div
          style={{
            width: '12%',
            display: 'flex',
            justifyContent: 'space-evenly',
          }}
        >
          <VideoCameraFilled />
          <span>LIVE: {liveTime}</span>
        </div>
        <div
          style={{
            width: '12%',
            display: 'flex',
            justifyContent: 'space-evenly',
          }}
        >
          <span>MC: 00:00:00</span>
        </div>
        <div
          style={{
            width: '12%',
            display: 'flex',
            justifyContent: 'space-evenly',
            marginRight: '10%',
          }}
        >
          <span>
            CPU: {deviceInfo.CPU}%,fps:{deviceInfo.frameRate}
          </span>
        </div>
      </div>
    </div>
  );
};
